accessid= 'LTAIpM7gKEjp9plr';
accesskey= 'COttQA9AhsDPkolIvsWwXwjNzCbdGI';
host = 'https://videotmp.oss-cn-shanghai.aliyuncs.com';

g_object_name = ''
g_object_name_type = ''
g_upload_url =''
now = timestamp = Date.parse(new Date()) / 1000; 

var policyText = {
    "expiration": "2029-01-01T12:00:00.000Z", //设置该Policy的失效时间，超过这个失效时间之后，就没有办法通过这个policy上传文件了
    "conditions": [
    ["content-length-range", 0, 3197152000] // 设置上传文件的大小限制
    ]
};

var policyBase64 = Base64.encode(JSON.stringify(policyText))
message = policyBase64
var bytes = Crypto.HMAC(Crypto.SHA1, message, accesskey, { asBytes: true }) ;
var signature = Crypto.util.bytesToBase64(bytes);

/**
 * 上传路径处理
 * @param userId
 * @returns {String}
 */
function get_dirname(userId)
{
	var upload_url='';
    if (userId != '')
    {
    	var myDate = new Date();
    	var year = myDate.getFullYear().toString();
    	var month =(myDate.getMonth()+1).toString();
    	var day= myDate.getDate().toString();
    	if(month<10){
    		month ='0' + month;
    	}
    	if(day<10){
    		day ='0' + day;
    	}
    	var upload_url=userId+'/source/';
    	var newDate=year+month+day;
    	upload_url=upload_url+newDate+'/';
    }
    return upload_url;
}

/**
 * 文件名处理
 * @param len
 * @returns {String}
 */
function random_string(len) {
	len = len || 32;
	var chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';   
	var maxPos = chars.length;
	var pwd = '';
	for (i = 0; i < len; i++) {
		pwd += chars.charAt(Math.floor(Math.random() * maxPos));
    }
    return pwd;
}
/**
 * 文件名后缀
 * @param filename
 * @returns {String}
 */
function get_suffix(filename) {
    pos = filename.lastIndexOf('.')
    suffix = ''
    if (pos != -1) {
        suffix = filename.substring(pos)
    }
    return suffix;
}

/**
 * 上传文件路径
 * @param filename
 * @param userId
 */
function calculate_object_name(filename,userId)
{
	suffix = get_suffix(filename)
	g_object_name= random_string(10)
    g_upload_url = get_dirname(userId) + g_object_name+ '/'+g_object_name + suffix
}

/**
 * 上传完成
 * @param filename
 * @returns
 */
function get_uploaded_object_name(filename)
{
    return filename;
}

/**
 * 文件上传
 * @param up
 * @param filename
 * @param ret
 * @param userId
 */
function set_upload_param(up, filename, ret, userId)
{
    if (filename != '') {
        suffix = get_suffix(filename)
        calculate_object_name(filename,userId)
    }
    new_multipart_params = {
        'key' : g_upload_url,
        'policy': policyBase64,
        'OSSAccessKeyId': accessid, 
        'success_action_status' : '200', //让服务端返回200,不然，默认会返回204
        'signature': signature,
    };

    up.setOption({
        'url': host,
        'multipart_params': new_multipart_params
    });

    up.start();
    return g_upload_url;
}

/**
 * 中止上传
 * @param up
 */
function stop_upload_file(up){
    up.stop();
}
